const { add } = require("lodash");

// promise一共有三个状态，分别为pending, fulfilled, rejected,用三个变量来存储这三个状态
const PENDING = 'pending';// 等待
const FULFILLED = 'fulfilled'; // 成功
const REJECTED = 'reject'; // 失败
class Mypromise {
  constructor(executor) { // 参数：执行器，接受一个函数
    try {
      executor(this.resolve, this.reject);// 接受两个参数，成功回调和失败回调
    } catch (e) {
      this.reject(e); // 异常监听，如果出现异常，则跑出错误，执行失败回调
    }
  }
  status = PENDING; // 配置初始promise的状态pending
  // 配置默认初始值，成功和失败
  value = undefined;
  reason = undefined;
  // 配置待执行的回调函数集合
  successCallback = [];
  failCallback = [];
  resolve = function (value) {
    // 如果状态不是等待，则阻止程序向下执行
    // 因为promise的状态只能发生一次转换
    // pending -> fulfilled || pending -> rejected
    if ( this.status !== PENDING ) return;
    // 将状态更改为成功
    this.status = FULFILLED;
    // 保存成功之后的值
    this.value = value;
    // 判断成功回调函数是否存在，如果存在则执行
    // 一个回调函数的情况
    this.successCallback && this.successCallback(this.value);
    // 如果回调函数比较多，则依次执行
    while (this.successCallback.length) {
      this.successCallback.shift()();
    }
  }
  reject = function (reason) {
    // 如果状态不是等待，则阻止程序向下执行
    if ( this.status !== PENDING ) return;
    // 将状态更改为失败
    this.status = REJECTED;
    // 保存失败之后的原因
    this.reason = reason;
    // 判断失败回调是否存在，如果存在则执行
    // 一个回调函数的情况
    this.failCallback && this.failCallback(this.reason);
    // 如果回调函数比较多，则依次执行
    while (this.successCallback.length) {
      this.successCallback.shift()();
    }
  }
  then = function (successCallback, failCallback) {
    // 参数可选
    successCallback = successCallback ? successCallback : value => value;
    // 参数可选
    failCallback = failCallback ? failCallback : reason => { throw reason };
    let promise2 = new Mypromise((resolve, reject) => {
      // 状态判断
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            // 判断x的值是普通值还是promise对象，如果是普通值，则直接调用resolve，如果是promise对象，则查看promise对象返回的结果，根据返回的结果决定是调用resolve还是reject
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else {
        // 等待，将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromise(promise2, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          });
        });
      }
    });
    return promise2;
  }
  finally = function (cb) {
    // 最终执行的函数，成功时返回value执行结果，失败时返回result失败原因
    // 调用静态方法resolve
    return this.then(value => {
      return Mypromise.resolve(cb()).then(() => value);
    }, reason => {
      return Mypromise.resolve(cb()).then(() => { throw reason });
    })
  }
  catch = function (failCallback) {
    // 如果中间过程中有错误，则执行最终的catch函数，没有resolve成功回调，只有reject失败回调函数
    return this.then(undefined, failCallback);
  }
  static all = function (array) {
    // promise调用集合
    // promise.all([p1, p2, p3]).then()
    let result = [];
    let index = 0; // 用于识别是否所有异步函数调用完毕
    return new Mypromise((resolve, reject) => {
      function addData (key, value) {
        result[key] = value;
        if (++index === array.length) { // 所有的异步函数都调用结束
          resolve(result);
        }
      }
      for (let i = 0; i < array.length; i++) {
        let current = array[i];
        if (current instanceof Mypromise) {
          // promise对象
          current.then(value => addData(i, value), reason => reject(reason));
        } else {
          // 普通值
          addData(i, array[i]);
        }
      }
    })
  }
  static resolve = function (value) {
    // 静态resolve方法，用于finally中的异步执行
    if (value instanceof Mypromise) {
      return value;
    }
    return new Mypromise(resolve => resolve(value));
  }
}

function resolvePromise (promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise...'));
  }
  
  if (x instanceof Mypromise) {
    // promise对象
    // x.then(value => resolve(value), reason => reject(reason));
    x.then(resolve, reject);
  } else {
    // 普通值
    resolve(x);
  }
}

module.exports = Mypromise;